<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>$Title$</title>
  <!--引入的vue.js-->
  <script src="/js/vue.js"></script>
  <!--引入elementUI的css-->
  <link type="text/css" rel="stylesheet" href="/css/index.css">
  <!--引入elementUI的js-->
  <script src="/js/index.js"></script>
  <!--引入axios.js-->
  <script src="/js/axios.min.js"></script>
  <style>
    /* 添加图片样式控制 */
    .scenic-image {
      width: 80px;
      height: 60px;
      object-fit: cover;
      border-radius: 4px;
      cursor: pointer;
      transition: transform 0.2s;
    }

    .scenic-image:hover {
      transform: scale(1.05);
    }

    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }

    .avatar {
      width: 100px;
      height: 100px;
      object-fit: cover;
      display: block;
    }

    /* 表格单元格样式调整 */
    .el-table .cell {
      padding: 4px 8px;
    }
  </style>
</head>
<body>
<div id="app">
  <!-- 搜索框-->
  <div class="search-container">
    <el-row :gutter="10">
      <el-col :span="4">
        <el-input v-model="searchForm.dotId" placeholder="请输入景点ID" clearable></el-input>
      </el-col>
      <el-col :span="4">
        <el-input v-model="searchForm.title" placeholder="请输入图片标题" clearable></el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      </el-col>
      <el-col :span="4">
        <el-button type="success" icon="el-icon-plus" @click="handleAdd">添加景点图片</el-button>
      </el-col>
      <el-col :span="4"></el-col>
    </el-row>
  </div>
  <el-table
          :data="tableData"
          style="width: 100%">
    <el-table-column
            prop="picId"
            label="图片id"
            width="180">
    </el-table-column>
    <el-table-column
            prop="dotId"
            label="景点ID"
            width="180">
    </el-table-column>
    <el-table-column
            prop="title"
            label="图片标题">
    </el-table-column>
    <el-table-column
            prop="spic"
            label="图片"
            width="120">
      <template slot-scope="scope">
        <div style="display: flex; justify-content: center; align-items: center; height: 70px;">
          <img v-if="scope.row.spic"
               :src="scope.row.spic"
               class="scenic-image"
               @error="$event.target.src='/img/default.jpg'"
               @click="previewImage(scope.row.spic)">
          <span v-else style="color: #909399; font-size: 12px;">无图片</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column
            prop="iscycle"
            label="是否轮转显示"
            width="180">
    </el-table-column>
    <el-table-column
            prop="summary"
            label="图片简述">
    </el-table-column>
    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button size="mini" type="primary" @click="handleEdit(scope.$index,scope.row)">编辑</el-button>
        <el-button size="mini" type="danger" @click="handleDelete(scope.$index,scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--    分页功能-->
  <!--分页  :相当于vue中v-bind 绑定属性  @相当于vue中v-on 绑定事件-->
  <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,10, 15, 20, 25]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
  </el-pagination>
  <!--添加/更新部门对话框-->
  <el-dialog title="title" :visible.sync="dialogFormVisible">
    <el-form :model="form" ref="form">
      <el-form-item label="景点ID" :label-width="formLabelWidth" prop="dotId" type="number">
        <el-input v-model="form.dotId" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="图片标题" :label-width="formLabelWidth" prop="title">
        <el-input v-model="form.title" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="图片" :label-width="formLabelWidth" prop="spic">
        <el-upload
                class="avatar-uploader"
                action="/scenicPic/uploadImage"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
                :before-upload="beforeAvatarUpload">
          <img v-if="form.spic" :src="form.spic" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="是否轮转显示：0-否，1-是" :label-width="formLabelWidth"prop="iscycle">
        <el-select v-model="form.iscycle" placeholder="请选择0或1">
          <el-option label="0" value="否"></el-option>
          <el-option label="1" value="是"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="图片简述" :label-width="formLabelWidth" prop="summary">
        <el-input v-model="form.summary" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="上传人ID" :label-width="formLabelWidth" prop="scrid" >
        <el-input v-model="form.scrid" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button @click="resetForm('form')">重 置</el-button>
      <!--            // 将对话框中的确定按钮修改为调用 submitForm 方法-->
      <el-button type="primary" @click="submitForm('form')">确 定</el-button>

    </div>
  </el-dialog>
</div>
<script>
  new Vue({
    el:"#app",
    data(){
      return{
        tableData:[],//列表数据
        searchForm:{},
        currentPage: 1, // 分页参数 ，第几页
        pageSize: 10,// 分页参数 ，每页显示条数
        total:500, // 分页参数，列表总条数
        dialogFormVisible: false, // 添加对话框是否显示
        title: '部门添加', // 弹出对话框的标题
        form: {  // 提交数据的form对象
          dotId:'',
          title:'',
          spic:'',
          iscycle:'',
          summary:'',
          scrid:'',
        },
        // 添加上传相关数据
        uploadHeaders: {
          // 如果需要认证token，可以在这里添加
        },
        fileList: [],
        formLabelWidth:"180px",
        rules:{
          dotId: [
            { required: true, message: '请输入景点ID', trigger: 'blur' },
            { type: 'number', message: '景点ID必须为数字', trigger: 'blur' },
          ],
          title: [{
            required: true, message: '请输入景区名称', trigger: 'blur'},
            { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
          ],
          spic: [
            { required: true, message: '请输入图片', trigger: 'blur' }
          ],
          iscycle: [
            { required: true, message: '是否轮转显示：0-否，1-是', trigger: 'blur' },
            { min: 0, max: 1, message: '请输入0或1', trigger: 'blur' }
          ],
          summary: [
            { required: true, message: '图片简述', trigger: 'blur' },
          ],
          scrid: [
            { required: true, message: '上传人员ID', trigger: 'blur' },
            { type: 'number', message: '上传人员ID必须为数字', trigger: 'blur' },
          ],
        },imageUrl: '',
      }
    },
    created(){
      this.loadData();
    },
    methods:{
      loadData(){
        this.loading=true;
        //定义this是vue对象
        let _this = this;
        // 向给定ID的用户发送post请求
        axios.post('/scenicPic/queryByPage', {
          "pageNo": this.currentPage,
          "pageSize": this.pageSize,
          "data": this.searchForm
        })
                .then(function(response) {
                  // 处理成功返回
                  console.log(response);
                  // 判断返回状态
                  if (response.data.code == 200) {
                    _this.tableData = response.data.data.list;
                    _this.total = response.data.data.total;
                  }
                })
                .catch(function(error) {
                  // 处理错误返回
                  console.log(error);
                  _this.$message.error('数据加载失败');
                })
                .finally(function() {
                  // 总是会执行
                  _this.loading = false;
                });
      },
      handleSizeChange(val) {
        console.log(`每页${val}条`);
        // 当前页码赋值
        this.pageSize = val;
        this.loadData();
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        // 当前页数量赋值
        this.currentPage = val;
        this.loadData();
      },
      // 搜索功能
      search() {
        this.currentPage = 1;
        this.loadData();
      },
      // 提交表单
      submitForm(f1) {
        this.$refs[f1].validate((valid) => {
          if (valid) {
            let method = 'post'; // 默认使用 POST
            let uri = '/scenicPic/add';

            if (this.title == '更新信息') {
              uri = '/scenicPic/update';
              method = 'put'; // 更新操作使用 PUT
            }

            let _this = this;

            // 根据方法选择不同的 axios 调用
            if (method === 'put') {
              axios.put(uri, this.form)
                      .then(function(response) {
                        _this.handleResponse(response);
                      })
                      .catch(function(error) {
                        _this.handleError(error);
                      });
            } else {
              axios.post(uri, this.form)
                      .then(function(response) {
                        _this.handleResponse(response);
                      })
                      .catch(function(error) {
                        _this.handleError(error);
                      });
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
// 添加响应处理函数
      handleResponse(response) {
        console.log(response);
        if (response.data.code == 200) {
          this.$message({
            message: '操作成功',
            type: 'success'
          });
          this.loadData();
          this.dialogFormVisible = false;
        } else {
          this.$message.error('操作失败: ' + response.data.msg)
        }
      },
// 添加错误处理函数
      handleError(error) {
        console.log(error);
        this.$message.error('操作出错: ' + error.message);
      },
      // 重置表单
      resetForm(f2) {
        this.$refs[f2].resetFields();
      },
      handleAdd(){
        this.dialogFormVisible = true;
        this.title = '添加图片';
        this.form={
          dotId:'',
          title:'',
          spic:'',
          iscycle:'',
          summary:'',
          scrid:'',
        };
      },
      // 处理更新
      handleEdit(index, row) {
        this.dialogFormVisible = true;
        this.title = '更新信息';
        this.form = JSON.parse(JSON.stringify(row));
      },
      // 处理删除
      // 修改删除方法，使用正确的 HTTP DELETE 方法
      handleDelete(index, row) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
                .then(() => {
                  let _this = this;
                  // 确保使用 DELETE 方法
                  axios.delete('/scenicPic/deleteById?dotId=' + row.dotId)
                          .then(function(response) {
                            console.log(response);
                            if (response.data.code == 200) {
                              _this.$message({
                                message: '删除成功',
                                type: 'success'
                              });
                              _this.loadData();
                            } else {
                              _this.$message.error('删除失败: ' + response.data.msg)
                            }
                          })
                          .catch(function(error) {
                            console.log(error);
                            _this.$message.error('删除出错: ' + error.message);
                          });
                }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 处理对话框关闭
      handleDialogClose(done) {
        this.$confirm('确认关闭？未保存的数据将会丢失')
                .then(_ => {
                  done();
                })
                .catch(_ => {});
      },
      // 处理图片上传成功
      handleAvatarSuccess(res, file) {
        if (res.code === 200) {
          // 修改这里：同时设置 spic 和 scover 字段
          this.form.spic = res.data.url;
          this.$message.success('图片上传成功');
        } else {
          this.$message.error('图片上传失败: ' + res.message);
        }
      },

      // 处理图片上传失败
      handleAvatarError(err, file, fileList) {
        this.$message.error('图片上传失败: ' + (err.message || '未知错误'));
      },

      // 图片上传前的检查
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt5M = file.size / 1024 / 1024 < 5;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
        }
        if (!isLt5M) {
          this.$message.error('上传图片大小不能超过 5MB!');
        }
        return isJPG && isLt5M;
      }
    }
  })
</script>
</body>
</html>